package com.itheima.travel.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.travel.dao.CategoryMapper;
import com.itheima.travel.pojo.Category;
import com.itheima.travel.service.CategoryService;
import com.itheima.travel.utils.JedisUtil;
import com.itheima.travel.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import redis.clients.jedis.Jedis;

import java.util.List;

public class CategoryServiceImpl implements CategoryService {
    @Override
    public String findCategoryAll() throws Exception {
        //获取Jedis对象
        Jedis jedis = JedisUtil.getJedis();
        //获取redis库中的缓存数据
        String categoryListJson = jedis.get("CategoryListJson");
        if(categoryListJson==null){
            // 没有缓存,查询mysql数据库
            System.out.println("查询mysql数据库,获取分类信息...");
            // 获取sqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            // 获取dao接口的实现类对象
            CategoryMapper mapper = sqlSession.getMapper(CategoryMapper.class);
            // 调用方法执行
            List<Category> list = mapper.findCategoryAll();
            // 将查询结果转成json字符串,存放到redis库中,并返回给web层
            ObjectMapper om = new ObjectMapper();
            categoryListJson = om.writeValueAsString(list);
            jedis.set("CategoryListJson",categoryListJson);
            // 关闭sqlSession对象
            MybatisUtils.closeSession(sqlSession);
        }
        //关闭jedis对象
        jedis.close();
        //返回json字符串
        return categoryListJson;
    }
}
